def load_cows(filename):
= {}
cows with open(filename, 'r') as f: # open file
for line in f: # iterate through each line in txt file
= line.strip().split(",") # split line
name, tons = int(tons) # Insert cow name and cow weight into dict
cows[name]
f.closereturn cows
1 6.0002 Problem Set 1: Space Cows Transportation
This is my assignment solution to a part of problemset 1 from this course: Introduction to Computational Thinking and Data Science
1.1 Part A: Transporting Cows
1.1.1 Problem A.1: Loading Cow Data
= load_cows('data/day27/ps1_cow_data.txt') cows
cows
{'Maggie': 3,
'Herman': 7,
'Betsy': 9,
'Oreo': 6,
'Moo Moo': 3,
'Milkshake': 2,
'Millie': 5,
'Lola': 2,
'Florence': 2,
'Henrietta': 9}
1.1.2 Problem A.2 Greedy Cow Transport
Result of function should be a list of lists with name of the given cows that can be transported for each run. Each list in the list is a new run
def greedy_cow_transport(cows: dict, max_weight):
= dict(sorted(cows.items(), key=lambda item: item[1], reverse=True))
cows_copy = []
transports
while len(cows_copy) > 0: # loop while the copy of cows is not empty
= [] # Initialize trip list
trip = 0 #
trip_weight for cow in list(cows_copy.keys()): # iterate through a list of the keys in the cows dict (necessary to avoid problem with pop function below
if (trip_weight+cows_copy[cow]) <= max_weight: # Check if the total trip weight plus the current cow is less than allowed weight
# If the cow fits on the trip, add to trip
trip.append(cow) += cows_copy[cow] # add current cow to total weight on trip
trip_weight # Remove current cow from the dictionary to not iterate through it again.
cows_copy.pop(cow) # when no more cows fit, append the current trip to transports lists
transports.append(trip) return transports
Solution
10) greedy_cow_transport(cows,
[['Betsy'],
['Henrietta'],
['Herman', 'Maggie'],
['Oreo', 'Moo Moo'],
['Millie', 'Milkshake', 'Lola'],
['Florence']]